package com.yonyou.gmcc.gateway.wechat.filter;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.marketing.common.util.CookieSecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.yonyou.gmcc.gateway.wechat.util.CookieUtil;
import com.yonyou.gmcc.gateway.wechat.util.TokenCheck;

@Service
public class AccessFilter extends ZuulFilter {
	@Autowired
	private TokenCheck tokenCheck;

	private static Logger log = LoggerFactory.getLogger(AccessFilter.class);

	@Override
	public Object run() {
		log.info("------进入gateway------");
		RequestContext ctx = RequestContext.getCurrentContext();

		HttpServletRequest request = ctx.getRequest();
		HttpServletResponse res = ctx.getResponse();
		
		String uri = request.getRequestURI();
        String code  = request.getParameter("code");
        log.info("------receivecode:"+code+",url="+request.getRequestURL());
        String method=request.getMethod();
        //微信验证服务器，不做权限验证
		if(uri.contains("wechatcall") && "GET".equals(method)){
		    log.info("微信验证服务器，不做权限验证");
            return null;
		}
		//分享的页面不做openid校验
		if(uri.contains("sharepage") ){
            log.info("分享的页面不做openid校验");
            return null;
        }
//        if(uri.contains("drive")){
//            log.info("试驾预约的页面不做openid校验");
//            return null;
//       }
	    if(uri.contains("showroom") ){
	         log.info("车型展厅的页面不做openid校验");
	         return null;
	    }
//	    if(uri.contains("personal")){
//            log.info("个人中心的页面:"+ request.getHeader("wechat_user_openid"));
//            return null;
//       }
//        if(uri.contains("counselors")||uri.contains("maintainDealerMap")||uri.contains("maintainDealer")||uri.contains("maintainSelectCity")||uri.contains("searchDealer")){
//            log.info("试驾预约查询接口不做openid校验");
//            return null;
//       }
		
		if(uri.contains("queryAdvisor") || uri.contains("getCountAdvisor") || uri.contains("getAdvisor"))
			return null;
		
		//接收微信的回调消息，取得openid并写入头转发到其他微服务
		if(uri.contains("wechatcall/request") && "POST".equals(method)){
		    log.info("接收微信的回调消息，取得openid并写入头转发到其他微服务");
	        String openid  = request.getParameter("openid");
	        log.info("------receiveopenid:"+openid+",url="+request.getRequestURL());
	        //tokenCheck.writeWechatCookiesInfo( openid, res);
	        tokenCheck.writeOpenidHeader(request, openid);
	        return null;
		}
		//接收微信的回调消息，取得openid并写入头转发到其他微服务
		if(uri.contains("wechatcall2/request") && "POST".equals(method)){
		    log.info("接收微信的回调消息，取得openid并写入头转发到其他微服务");
	        String openid  = request.getParameter("openid");
	        log.info("------receiveopenid:"+openid+",url="+request.getRequestURL());
	        //tokenCheck.writeWechatCookiesInfo( openid, res);
	        tokenCheck.writeOpenidHeader(request, openid);
	        return null;
		}
		//转发请求到微服务，验证cookie中是否包含openid，并取得openid并写入头转发到其他微服务
//        tokenCheck.writeOpenidHeader(request, a[1]);
		if(request.getHeader("Referer").indexOf("openId")>0){
	        String a[] = request.getHeader("Referer").split("openId=");
	        log.info("获取请求头："+a[1]);
	        String openId = a[1];
	        if(openId.length()==128){
	            try {
	                openId = CookieSecurityUtil.decrypt(a[1]);
	                String b[] = openId.split(",,");
	                log.info("解密后的openId为："+b[0]);
	                CookieUtil.writeOpenid(b[0], res);
	                tokenCheck.writeOpenidHeader(request, b[0]);
	            } catch (Exception e) {
	                log.error(e.getMessage());
	            }
	        }else{
		        CookieUtil.writeOpenid(a[1], res);
		        tokenCheck.writeOpenidHeader(request, a[1]);
	        }
	        return null;
		}
		if(request.getHeader("Referer").indexOf("WECHAT_USER_OPENID")>0){
            String a[] = request.getHeader("Referer").split("WECHAT_USER_OPENID=");
            log.info("获取请求头："+a[1]);
            String openId = null;
            try {
                openId = CookieSecurityUtil.decrypt(a[1]);
                String b[] = openId.split(",,");
                log.info("解密后的openId为："+b[0]);
                CookieUtil.writeOpenid(b[0], res);
                tokenCheck.writeOpenidHeader(request, b[0]);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            return null;
        }
		log.info("转发请求到微服务-start");
		if (!tokenCheck.check(request, res)) {
			log.warn("------access token not pass");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(res.getStatus());
			return null;
		}
		log.info("结束");
		return null;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	/**
	 * 获取登录用户远程主机ip地址
	 * 
	 * @param request
	 * @return
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
